import { Component, OnInit } from '@angular/core';

import { Storage } from '@ionic/storage';

import { NavController, ActionSheetController, AlertController } from 'ionic-angular';
import { Config } from '../../../providers/config';

import { Common } from '../../../providers/common';
import { DomSanitizer } from '@angular/platform-browser';
import _ from 'lodash';
import { MarketingProductionMangeService } from "./mange.service";

@Component({
  selector: 'page-marketing-production-manege',
  templateUrl: './mange.html',

  providers: [MarketingProductionMangeService]
})
export class MarketingProductionMangePage {
  moa_page_name: any = "page-marketing-mange";
  moa_page_explain: any = "产品管理";
  hasOpAuth = false
  tableData
  showleft = []

  constructor(public navCtrl: NavController,
    public alertCtrl: AlertController,
    public mangeService: MarketingProductionMangeService,
    private sanitizer: DomSanitizer,
    private actionSheetCtrl: ActionSheetController,
    public storage: Storage,
    public common: Common
  ) {
  }

  ngAfterViewInit(): void {
    let loginid: string,
      org: string;
    this.storage.get("userInfo").then(user => {
      let that = this;
      loginid = user.loginid;
      org = user.orgname;
      let parmas = {
        "name": loginid,
        "titleid": 1005
      }
      this.mangeService.getAnalyDataFromRedis(parmas).subscribe((res: any) => {
        this.hasOpAuth = res.isAdmin;
        if (res.requestData) {
          this.processData(res.requestData);
        }
      });
    });
  }

  processData(requestData) {
    console.log(requestData)
    //带有描述的字段移至首位
    _.forEach(requestData.data, items => {
      _.forEach(items.data, (item, index) => {
        if (item.col8) {
          let desItem = items.data[index];
          items.data.splice(index, 1);
          items.data.unshift(desItem);
          //items.data.unshift(items.data.splice(index, 1));
        }
      })
    });

    //描述内容箭头替换
    _.forEach(requestData.data, item => {
      if (item.data[0].col8) {
        let des = item.data[0].col8; //描述内容

        item.data[0].col8 = des.replace(/([^\d])\-([0-9]*[\.]*[0-9]*\S{1})/g, "$1<span class='fall'>↓ $2</span>"); //替换"-"
        item.data[0].col8 = item.data[0].col8.replace(/([^\d])\+([0-9]*[\.]*[0-9]*\S{1})/g, "$1<span class='rise'>↑ $2</span>"); //替换"+"
      }
    });

    this.tableData = requestData.data;
    _.forEach( this.tableData, item => {
      let leftItem = {
        "id": null,
        "col": [],
        "title": []
      }
      leftItem["id"] = item["option"]["id"];
      _.forEach( item.data, data => {
        _.forEach( data, (val, key) => {
          if((/[\u4e00-\u9fa5]+/).test(val) && key != "col8") {
            leftItem.col.push(key)
          }
        })
      })
      leftItem. col = _.uniq(leftItem.col);
      this.showleft.push(leftItem);
    })
    console.log(this.tableData)
  }

  setBgColor(item, tableid) {
    if (tableid == 100045) {
      let topareaname = item['topareaname'];
      let blueColor = ["渠道发行"];
      if (blueColor.indexOf(topareaname) > -1) {
        return "bg-blue"
      }
    }
  }

  setPosition(key, tableid) {
    
    let leftArr = _.find(this.showleft, {id: tableid})["col"];
    
    if(leftArr.indexOf(key) > -1) {
      return "showleft"
    }
  }

  getKeys(item){
    return Object.keys(item);
  }
  /**
 * 更多操作
 */
  moreOp() {
    let bottons = [{
      text: '生成',
      handler: () => {
        this.storage.get("userInfo").then(user => {
          let loginid = user.loginid;
          let org = user.orgname;
          let titleid: number = 1005;
          this.mangeService.generateUSPAnalyData(loginid, titleid).subscribe((res: any) => {
            if (res) {
              if (res.isSuccess) {
                this.common.alertMessage("数据生成成功！");
                this.processData(res.requestData);
              } else {
                this.common.alertMessage("数据生成失败！");
              }
            }
          })
          console.log('点击生成按钮');
        });
      }
    }, {
      text: '发布',
      handler: () => {
        let confirm = this.alertCtrl.create({
          title: '提示',
          message: "您确定要发布吗？",
          enableBackdropDismiss: false,
          buttons: [{
            text: '取消',
            role: 'cancel',
            handler: () => {

            }
          }, {
            text: '确定',
            handler: () => {
              this.storage.get("userInfo").then(user => {
                let loginid = user.loginid;
                let org = user.orgname;
                let titleid: number = 1005;
                this.mangeService.publishUSBMobileAnalyData(titleid).subscribe((res: any) => {
                  if (res) {
                    if (res.isSuccess) {
                      this.common.alertMessage("数据发布成功！");
                      this.processData(res.requestData);
                    } else {
                      this.common.alertMessage("数据发布失败！");
                    }
                  }
                })
              });
            }
          }]
        });
        confirm.present();
      }
    }, {
      text: '回滚',
      handler: () => {
        let confirm = this.alertCtrl.create({
          title: '提示',
          message: "您确定要回滚吗？",
          enableBackdropDismiss: false,
          buttons: [{
            text: '取消',
            role: 'cancel',
            handler: () => {

            }
          }, {
            text: '确定',
            handler: () => {
              this.storage.get("userInfo").then(user => {
                let loginid = user.loginid;
                let org = user.orgname;
                let titleid: number = 1005;
                this.mangeService.rollBackUSBMobileAnalyData(titleid).subscribe((res: any) => {
                  if (res) {
                    if (res.isSuccess) {
                      this.common.alertMessage("数据回滚成功！");
                      this.processData(res.requestData);
                    } else {
                      this.common.alertMessage("数据回滚失败！");
                    }
                  }
                })
              });
            }
          }]
        });
        confirm.present();
      }
    }, {
      text: '取消',
      role: 'cancel',
      handler: () => {
      }
    }];

    let actionSheet = this.actionSheetCtrl.create({
      title: '',
      buttons: bottons
    });
    actionSheet.present();
  }
}


